<?php

/**
 * Name: 系统通知记录仓储层
 * User: Silent
 * Date: 2025-11-07
 * Time: 15:30:00
 */

namespace App\Repositories\Checkin;

use App\Models\Checkin\NotificationLog;
use App\Repositories\BaseRepository;

class NotificationLogRepository extends BaseRepository
{
    public function __construct(NotificationLog $model)
    {
        parent::__construct($model);
    }

    /**
     * 创建通知记录
     */
    public function createNotification($notificationData)
    {
        return $this->create([
            'notification_type' => $notificationData['type'],
            'recipient_id' => $notificationData['recipient_id'],
            'recipient_name' => $notificationData['recipient_name'],
            'related_id' => $notificationData['related_id'] ?? null,
            'related_date' => $notificationData['related_date'] ?? null,
            'message_content' => $notificationData['message_content'] ?? null,
            'send_status' => NotificationLog::STATUS_PENDING,
        ]);
    }

    /**
     * 获取待发送的通知
     */
    public function getPendingNotifications($limit = 100)
    {
        return $this->query()
            ->where('send_status', NotificationLog::STATUS_PENDING)
            ->orderBy('created_at')
            ->limit($limit)
            ->get();
    }

    /**
     * 标记通知为已发送
     */
    public function markAsSent($id, $result = null)
    {
        return $this->update($id, [
            'send_status' => NotificationLog::STATUS_SUCCESS,
            'send_result' => $result,
            'sent_at' => now()
        ]);
    }

    /**
     * 标记通知为发送失败
     */
    public function markAsFailed($id, $result = null)
    {
        return $this->update($id, [
            'send_status' => NotificationLog::STATUS_FAILED,
            'send_result' => $result,
            'sent_at' => now()
        ]);
    }

    /**
     * 获取通知记录列表
     */
    public function getNotificationLogs($perPage = 15, $filters = [])
    {
        $query = $this->query();

        // 通知类型筛选
        if (isset($filters['notification_type'])) {
            $query->where('notification_type', $filters['notification_type']);
        }

        // 接收人筛选
        if (isset($filters['recipient_id'])) {
            $query->where('recipient_id', $filters['recipient_id']);
        }

        // 发送状态筛选
        if (isset($filters['send_status'])) {
            $query->where('send_status', $filters['send_status']);
        }

        // 日期筛选
        if (isset($filters['start_date'])) {
            $query->where('created_at', '>=', $filters['start_date']);
        }
        if (isset($filters['end_date'])) {
            $query->where('created_at', '<=', $filters['end_date']);
        }

        return $query->with('recipient')
                    ->orderBy('created_at', 'desc')
                    ->paginate($perPage);
    }

    /**
     * 获取指定用户的通知记录
     */
    public function getUserNotifications($recipientId, $perPage = 15, $filters = [])
    {
        $query = $this->query()->where('recipient_id', $recipientId);

        // 通知类型筛选
        if (isset($filters['notification_type'])) {
            $query->where('notification_type', $filters['notification_type']);
        }

        // 发送状态筛选
        if (isset($filters['send_status'])) {
            $query->where('send_status', $filters['send_status']);
        }

        return $query->orderBy('created_at', 'desc')
                    ->paginate($perPage);
    }

    /**
     * 获取通知统计信息
     */
    public function getNotificationStatistics($startDate = null, $endDate = null)
    {
        $query = $this->query();

        if ($startDate) {
            $query->where('created_at', '>=', $startDate);
        }
        if ($endDate) {
            $query->where('created_at', '<=', $endDate);
        }

        return [
            'total' => $query->count(),
            'pending' => $query->clone()->where('send_status', NotificationLog::STATUS_PENDING)->count(),
            'success' => $query->clone()->where('send_status', NotificationLog::STATUS_SUCCESS)->count(),
            'failed' => $query->clone()->where('send_status', NotificationLog::STATUS_FAILED)->count(),
            'by_type' => $query->clone()->selectRaw('notification_type, COUNT(*) as count')
                              ->groupBy('notification_type')
                              ->get()
                              ->pluck('count', 'notification_type')
                              ->toArray(),
        ];
    }

    /**
     * 删除过期的通知记录（可选功能）
     */
    public function deleteExpiredNotifications($days = 30)
    {
        $expiredDate = now()->subDays($days);
        
        return $this->query()
            ->where('created_at', '<', $expiredDate)
            ->where('send_status', '!=', NotificationLog::STATUS_PENDING)
            ->delete();
    }

    /**
     * 重试失败的通知
     */
    public function retryFailedNotifications($limit = 50)
    {
        return $this->query()
            ->where('send_status', NotificationLog::STATUS_FAILED)
            ->orderBy('created_at')
            ->limit($limit)
            ->update(['send_status' => NotificationLog::STATUS_PENDING]);
    }
}

